package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"lottery/comm"
	"lottery/models"
	"lottery/services"
	"net/http"
	"strconv"
)

// 后台优惠券管理控制器创建
type AdminUserController struct {
	ServiceUser    services.UserService
	ServiceGift    services.GiftService
	ServiceCode    services.CodeService
	ServiceResult  services.ResultService
	ServiceUserday services.UserdayService
	ServiceBlackip services.BlackipService
}

func (adu *AdminUserController) Get(c *gin.Context) {
	// 获取url 中的参数, id, page, 并转为int类型
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size := 10 // 默认页面大小为 100
	// 数据列表构建, 总数
	var (
		total    int
		pagePrev string // 上下页码
		pageNext string
		datalist []models.LtUser
	)
	// 数据
	datalist = adu.ServiceUser.GetAll(page, size)
	total = (page-1)*size + len(datalist)
	// 数据总数
	if len(datalist) >= size {
		total = int(adu.ServiceUser.CountAll())
		pageNext = fmt.Sprintf("%d", page-1)
	}
	if page > 1 {
		pagePrev = fmt.Sprintf("%d", page+1)
	}

	// 模板渲染数据
	c.HTML(http.StatusOK, "admin/user", gin.H{
		"Title":    "管理后台",
		"Channel":  "user",
		"Datalist": datalist,
		"Total":    total,
		"Now":      comm.NowUnix(),
		"PagePrev": pagePrev,
		"PageNext": pageNext,
	})
}

// 黑一周，黑一个月，黑一年
// 更新黑名单的字段， 时间改一下
func (adu *AdminUserController) GetBlack(c *gin.Context) {
	userId, _ := strconv.Atoi(c.DefaultQuery("id", "0"))
	t, _ := strconv.Atoi(c.DefaultQuery("time", "0"))
	if userId > 0 {
		t = t*86400 + comm.NowUnix()
		// 更新到数据库
		_ = adu.ServiceUser.Update(&models.LtUser{Id: userId,
			BlackTime: t, SysUpdated: comm.NowUnix()},
			[]string{"blacktime", "sys_updated"})
	}

	// 重定向
	c.Redirect(http.StatusFound, "/admin/user")
}
